<%@ page import="java.util.Objects" %>
<%@ page import="java.net.URLDecoder" %>
<%@ page import="static java.awt.SystemColor.window" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String username = null;
    Cookie cookie = null;
    Cookie[] cookies = null;
    // 获取cookies的数据,是一个数组
    cookies = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            cookie = cookies[i];
            if (Objects.equals(cookie.getName(), "username")) {
                username = URLDecoder.decode(cookie.getValue(), "utf-8");
                break;
            }
        }
    }
    if (username != null) {
        response.sendRedirect("/Mall/product/list");
    }
%>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Login Page</title>
    <link rel="stylesheet" href="css/font-awesome-4.7.0/font-awesome-4.7.0/css/font-awesome.min.css">
    <!--    <link rel="stylesheet" href="css/bootstrap.min.css">-->
    <!--    <link rel="stylesheet" type="text/css" href="css/bootstrap-4.6.0-dist/css/bootstrap.min.css"/>-->
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-image: url('./img/background.png');
            background-size: cover;
            background-position: center;
        }

        .container {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
        }

        .login-box {
            background-color: rgba(255, 255, 255, 0.7); /* 透明度为0.7的白色背景 */
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            padding: 20px;
            width: 300px;
        }

        .login-box h2 {
            text-align: center;
            margin-bottom: 20px;
        }

        .login-box input[type="text"],
        .login-box input[type="password"] {
            width: 100%;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
            margin-bottom: 15px;
            box-sizing: border-box;
        }

        .login-box input[type="submit"] {
            width: 100%;
            background-color: #4caf50;
            color: #fff;
            border: none;
            padding: 10px;
            border-radius: 5px;
            cursor: pointer;
        }

        .login-box input[type="submit"]:hover {
            background-color: #45a049;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="login-box">
        <!--        用户登录-->
        <h2>用户登录</h2>
        <%--        <form id="loginForm" onsubmit="sublim(event)">--%>
        <form id="loginForm" action="/Mall/product/login" method="post" onsubmit="sublim(event)">
            <input type="text" name="username" placeholder="请输入用户名" required id="username">
            <input type="password" name="password" placeholder="请输入密码" required id="pwd">
            <div style="display: flex; align-items: center;">
                <input class="form-control" placeholder="验证码" type="text" name="safeCode" id="safeCode" required>
                <canvas id="canvas" width="100" height="43" onclick="dj()"
                        style="border: 1px solid #ccc;
                        border-radius: 5px;"></canvas>
            </div>
            <input type="submit" value="登录">
            <a href="register.html" id="nav1">注册</a>
        </form>

    </div>
</div>
</body>
<script src="./js/jquery.min.js" type="text/javascript"></script>
<script src="js/http_cdn.bootcdn.net_ajax_libs_jsencrypt_3.3.2_jsencrypt.js"></script>
<script>
    var show_num = [];
    draw(show_num);

    function dj() {
        draw(show_num);
    }

    function getPublickKey(event) {
        // 阻止表单的默认提交行为
        event.preventDefault();
        // 发送请求获取公钥
        $.ajax({
            url: "${pageContext.request.contextPath}/product/getPublicKey?username=" + document.getElementById("username").value,
            type: "get",
            success: function (data) {
                var publicKey = '-----BEGIN PUBLIC KEY-----' + data + '-----END PUBLIC KEY-----';
                var encrypt = new JSEncrypt();
                encrypt.setPublicKey(publicKey);
                var pwd = document.getElementById("pwd").value;
                var username = document.getElementById("username").value;
                pwd = encrypt.encrypt(pwd);
                document.getElementById("pwd").value = pwd;
                // 手动提交表单
                document.getElementById("loginForm").submit();
                // 清空表单
                document.getElementById("username").value = '';
                document.getElementById("pwd").value = '';
                document.getElementById("safeCode").value = '';
            }
        });
    }

    function sublim(event) {
        var val = document.getElementById("safeCode").value;
        var username = document.getElementById("username").value;
        var num = show_num.join("");
        console.log("bef", num)
        if (val == '') {
            event.preventDefault(); // 阻止表单提交
        } else if (val.toLowerCase() == num.toLowerCase()) {
            let expiresDate = new Date();
            expiresDate.setDate(expiresDate.getDate() + 3);  // 设置cookie值 5天后过期
            if (username.trim() != "") {   // trim() 去掉cookie字段值前后的空格。
                document.cookie = "username=" + username + ";expires=" + expiresDate;
            }
            // 调用加密方法
            getPublickKey(event);
            draw(show_num);
        } else {
            console.log(val)
            console.log(num)
            event.preventDefault(); // Prevent form submission
            alert('验证码错误，请重新输入。');
            document.getElementById("text").value = '';
            draw(show_num);
        }
    }

    function draw(show_num) {
        var canvas_width = document.getElementById('canvas').clientWidth;
        var canvas_height = document.getElementById('canvas').clientHeight;
        var canvas = document.getElementById("canvas");//获取到canvas的对象，演员
        var context = canvas.getContext("2d");//获取到canvas画图的环境，演员表演的舞台
        canvas.width = canvas_width;
        canvas.height = canvas_height;
        var sCode = "A,B,C,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,W,X,Y,Z,1,2,3,4,5,6,7,8,9,0,q,w,e,r,t,y,u,i,o,p,a,s,d,f,g,h,j,k,l,z,x,c,v,b,n,m";
        var aCode = sCode.split(",");
        var aLength = aCode.length;//获取到数组的长度

        for (var i = 0; i <= 3; i++) {
            var j = Math.floor(Math.random() * aLength);//获取到随机的索引值
            var deg = Math.random() * 30 * Math.PI / 180;//产生0~30之间的随机弧度
            var txt = aCode[j];//得到随机的一个内容
            show_num[i] = txt;
            var x = 10 + i * 20;//文字在canvas上的x坐标
            var y = 20 + Math.random() * 8;//文字在canvas上的y坐标
            context.font = "bold 23px 微软雅黑";

            context.translate(x, y);
            context.rotate(deg);

            context.fillStyle = randomColor();
            context.fillText(txt, 0, 0);

            context.rotate(-deg);
            context.translate(-x, -y);
        }
        for (var i = 0; i <= 5; i++) { //验证码上显示线条
            context.strokeStyle = randomColor();
            context.beginPath();
            context.moveTo(Math.random() * canvas_width, Math.random() * canvas_height);
            context.lineTo(Math.random() * canvas_width, Math.random() * canvas_height);
            context.stroke();
        }
        for (var i = 0; i <= 30; i++) { //验证码上显示小点
            context.strokeStyle = randomColor();
            context.beginPath();
            var x = Math.random() * canvas_width;
            var y = Math.random() * canvas_height;
            context.moveTo(x, y);
            context.lineTo(x + 1, y + 1);
            context.stroke();
        }
    }

    function randomColor() {//得到随机的颜色值
        var r = Math.floor(Math.random() * 256);
        var g = Math.floor(Math.random() * 256);
        var b = Math.floor(Math.random() * 256);
        return "rgb(" + r + "," + g + "," + b + ")";
    }
</script>
</html>
